package cn.rkylin.oms.aftersale.resend.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.ApolloMap;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.aftersale.resend.dao.IAfterSaleResendDAO;
import cn.rkylin.oms.aftersale.resend.dao.IAfterSaleResendSkuDAO;
import cn.rkylin.oms.aftersale.resend.domain.AfterSaleResend;
import cn.rkylin.oms.aftersale.resend.domain.AfterSaleResendSku;
import cn.rkylin.oms.aftersale.resend.service.IAfterSaleResendService;
import cn.rkylin.oms.aftersale.resend.vo.ResendVO;
import cn.rkylin.oms.aftersale.resend.vo.ResultdSkuVO;
import cn.rkylin.oms.aftersale.sysrefund.servcie.impl.SysRefundServiceImpl;
import cn.rkylin.oms.common.consts.ResendCancelStatus;
import cn.rkylin.oms.common.consts.ResendStatus;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.utils.CodeUtil;
import cn.rkylin.oms.order.dao.IOrderDAO;
import cn.rkylin.oms.order.vo.OrderVO;
import cn.rkylin.oms.system.logistics.domain.Logistics;
import cn.rkylin.oms.system.logistics.service.ILogisticsService;
import cn.rkylin.oms.system.project.service.ProjectManagerService;
import cn.rkylin.oms.system.project.vo.ProjectVO;
import cn.rkylin.oms.system.shop.domain.Shop;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.system.stockpush.service.IStockPushService;
import cn.rkylin.oms.system.storage.domain.Stor;
import cn.rkylin.oms.system.storage.service.IStorService;
import cn.rkylin.oms.warehouse.shiporder.service.IShiporderService;
import cn.rkylin.oms.warehouse.shiporder.util.SnCodeExtractor;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderSkuVO;
import cn.rkylin.oms.warehouse.shiporder.vo.ShiporderVO;
import cn.rkylin.oms.warehouse.stock.service.IStockService;
import cn.rkylin.oms.warehouse.stock.vo.StockVO;

/**
 * 类名:AfterSaleResendServiceImpl <br/>
 * 作用: 补发单服务层实现. <br/>
 * 创建原因: 对补发单提供对外实现. <br/>
 * 创建时间: 2017年11月7日 下午2:20:00 <br/>
 *
 * @author liPeng
 * @version v1.0
 */
@Service("resendService")
public class AfterSaleResendServiceImpl extends ApolloService implements IAfterSaleResendService {
    private static final Log logger = LogFactory.getLog(SysRefundServiceImpl.class);
    private static final String STATEMENT_SELECT_COUNT_BY_STATUS = "selectResendCounts";

    /**
     * resendDAO:补发单数据访问层.
     */
    @Autowired
    public IAfterSaleResendDAO resendDAO;
    
    @Autowired
    private SnCodeExtractor snCodeExtractor;

    /**
     * resendSkuDAO:补发明细单数据访问层.
     */
    @Autowired
    public IAfterSaleResendSkuDAO resendSkuDAO;

    /**
     * orderService:订单服务层
     */
    @Autowired
    public IOrderDAO orderDao;

    /**
     * shopService:店铺服务层
     */
    @Autowired
    public IShopService shopService;

    /**
     * shiporderService:发货服务层
     */
    @Autowired
    public IShiporderService shiporderService;

    /**
     * stockService:库存服务接口
     */
    @Autowired
    public IStockService stockService;

    /**
     * 仓库服务层
     */
    @Autowired
    public IStorService storService;

    /**
     * 物流公司服务层
     */
    @Autowired
    public ILogisticsService logisticsService;

    /**
     * 项目服务层
     */
    @Autowired
    private ProjectManagerService projectManagerService;

    @Autowired
    private IStockPushService stockPushService;

    /**
     * getResendListByCondition:条件查询补发单列表. <br/>
     *
     * @param page
     * @param length
     * @param queryParamVO
     * @return
     * @throws Exception
     */
    public PageInfo<ResendVO> getResendListByCondition(int page, int length, ResendVO queryParamVO) throws Exception {
        PageInfo<ResendVO> returnValue = null;
        logger.info("开始执行补发单查询...");
        try {
            returnValue = resendDAO.pageSelectByCondition(page, length, queryParamVO);
            logger.info("开始执行补发单查询...");
        } catch (Exception e) {
            logger.info("执行补发单查询出现错误".concat(e.getMessage()));
            throw e;
        }
        return returnValue;
    }

    /**
     * getResend:根据补发单ID获取补发单明细.
     *
     * @param resendId
     * @return
     */
    public AfterSaleResend getResendById(String resendId) throws Exception {
        AfterSaleResend returnValue = resendDAO.selectByPrimaryKey(resendId);
        return returnValue;
    }

    /**
     * cancelResend:取消补发单
     */
    public String cancelResend(AfterSaleResend resend) throws Exception {
        String returnMsg = "";
        if (ResendStatus.DELIVER.equals(resend.getResendStatus()) && ResendCancelStatus.N.equals(resend.getCancelStatus())) {
            // 调用出库单接口
            ShiporderVO shiporderVO = new ShiporderVO();
            shiporderVO.setSourceId(resend.getResendId());
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            // 设置项目Id
            String prjId = currentUser.getCurrentProject().getPrjId();
            shiporderVO.setPrjId(prjId);
            PageInfo<ShiporderVO> shiporderVOList = findPage(0, Integer.MAX_VALUE, "pageSelectShiporder", shiporderVO);
            List<ShiporderVO> shiporderDataList = shiporderVOList.getList();

            if (shiporderDataList != null && shiporderDataList.size() > 0) {
                String shiporderId = shiporderDataList.get(0).getShiporderId();
                String result = shiporderService.cancelShiporder(shiporderId);
                if ("取消成功".equals(result)) {
                    cancelResendAfterCancelShiporder(resend.getResendId());
                    returnMsg = "取消成功";
                } else {
                    returnMsg = "发货单取消失败，补发单取消失败";
                }
            }

        }
        return returnMsg;
    }

    public void cancelResendAfterCancelShiporder(String resendId) throws Exception {
        // 根据补发单id查询补发单
        ResendVO result = getResendDetailById(resendId);
        result.setCancelStatus(ResendCancelStatus.Y);
        result.setUpdateTime(new Date());
        int ires = resendDAO.updateByPrimaryKeySelective(result);
        if (ires > 0) {
            // 更新系统订单补发单的状态
            // 通过补发单单id获取订单id
            String strSourceId = result.getSourceId();
            if (StringUtils.isNotBlank(strSourceId)) {
                // 通过来源id获取未废弃补发单信息
                List<AfterSaleResend> afterSaleResendBySourceID = resendDAO.selectResendBySourceID(strSourceId);
                if (afterSaleResendBySourceID == null || afterSaleResendBySourceID.size() <= 0) {
                    // 没有 未废弃的补发单，更新订单补发单标识为 n
                    OrderVO orderVOUpdate = new OrderVO();
                    orderVOUpdate.setOrderId(strSourceId);
                    orderVOUpdate.setHasResend("n");
                    int iOrderUpdate = orderDao.update(orderVOUpdate);
                }
            }
        }
    }

    public void updateResendStatusAfterCancelShiporder(String resendId) throws Exception {
        // 根据补发单id查询补发单
        ResendVO result = getResendDetailById(resendId);
        result.setResendStatus(ResendStatus.VERIFY);
        result.setUpdateTime(new Date());
        resendDAO.updateByPrimaryKeySelective(result);
    }

    /**
     * saveResends：保存补发单
     */
    public String saveResends(ResendVO resendVO) throws Exception {
        String returnMsg = "";
        // 根据来源单号查询订单
        String orderId = resendVO.getSourceId();
        OrderVO order = orderDao.findById(orderId);
        // 至少有一条商品信息
        List<AfterSaleResendSku> list = resendVO.getResendSkuList();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getQty() == null) {
                    returnMsg = "补发单数量不能为0";
                    return returnMsg;
                }
            }
            if (StringUtils.isEmpty(resendVO.getResendId())) {
                // 新增补发单
                ResendVO resend = getResendVODetail(resendVO, order);
                int insertResend = resendDAO.insert(resend);

                if (insertResend > 0) {
                    // 更新系统订单补发单的状态
                    OrderVO orderVOUpdate = new OrderVO();
                    orderVOUpdate.setOrderId(orderId);
                    orderVOUpdate.setHasResend("y");
                    int iOrderUpdate = orderDao.update(orderVOUpdate);
                }

                // 保存补发单商品信息
                Boolean saveResendSku = saveResendSkus(resend, list);
                if (insertResend > 0 && saveResendSku) {
                    returnMsg = "添加成功";
                }
            } else {
                // 清空补发单对应的明细
                delResendSku(resendVO);
                // 更新补发单
                ResendVO resend = getResendVODetail(resendVO, order);
                int updateUpdate = resendDAO.updateByPrimaryKeySelective(resend);
                // 保存补发单商品信息
                Boolean saveResendSku = saveResendSkus(resend, list);
                if (updateUpdate > 0 && saveResendSku) {
                    returnMsg = "修改成功";
                }
            }
        } else {
            returnMsg = "请至少添加有一条商品信息";
        }
        return returnMsg;
    }

    /**
     * getResendVODetail:为保存补发单准备数据
     *
     * @param resendVO
     * @param order
     * @return
     */
    private ResendVO getResendVODetail(ResendVO resendVO, OrderVO order) throws Exception {
        // 创建时间
        if (StringUtils.isEmpty(resendVO.getResendId())) {
            resendVO.setCreateTime(new Date());
        }
        // 修改时间
        resendVO.setUpdateTime(new Date());
        // 补发单Id/code
        if (StringUtils.isEmpty(resendVO.getResendId())) {
            resendVO.setResendId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
            resendVO.setResendCode(generateReturnCodeWithType("RS", order.getShopId()));
        }
        // ent_id 企业Id
        if (StringUtils.isEmpty(resendVO.getEntId())) {
            resendVO.setEntId(order.getEntId());
        }
        // 获取当前登录人
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        // 获取当前登录人所属项目
        String projectId = currentUser.getCurrentProject().getPrjId();

        // prj_id 项目Id
        if (StringUtils.isEmpty(resendVO.getPrjId())) {
            resendVO.setPrjId(projectId);
        }
        // 店铺Id
        resendVO.setShopId(order.getShopId());
        // 店铺名称
        if (StringUtils.isEmpty(resendVO.getShopName())) {
            resendVO.setShopName(order.getShopName());
        }
        // 补发单编号
        // if (StringUtils.isEmpty(resendVO.getResendCode())) {
        // resendVO.setResendCode(generateReturnCodeWithType("RS",
        // order.getShopId()));
        // //
        // resendVO.setResendCode(java.util.UUID.randomUUID().toString().replaceAll("-",
        // // ""));
        // }
        // 删除标记
        // resendVO.setDeleted("n");
        // source_type 来源类型(or订单)
        resendVO.setSourceType("or");
        // 补发单状态
        // if (StringUtils.isEmpty(resendVO.getResendStatus())) {
        // resendVO.setResendStatus("a");
        // }
        // 买家收货人
        if (StringUtils.isEmpty(resendVO.getCons())) {
            resendVO.setCons(order.getCons());
        }
        // 买家昵称(客户ID)
        // if (StringUtils.isEmpty(resendVO.getBuyerNick())) {
        // resendVO.setBuyerNick(order.getBuyerNick());
        // }
        // 买家电话
        if (StringUtils.isEmpty(resendVO.getConsTel())) {
            resendVO.setConsTel(order.getConsTel());
        }
        // 买家手机
        if (StringUtils.isEmpty(resendVO.getConsMobile())) {
            resendVO.setConsMobile(order.getConsMobile());
        }
        // 买家地址
        if (StringUtils.isEmpty(resendVO.getConsAddr())) {
            resendVO.setConsAddr(order.getConsAddr());
        }
        // 省名称
        if (StringUtils.isEmpty(resendVO.getProvName())) {
            resendVO.setProvName(order.getProvName());
        }
        // 市名称
        if (StringUtils.isEmpty(resendVO.getCityName())) {
            resendVO.setCityName(order.getCityName());
        }
        // 区名称
        if (StringUtils.isEmpty(resendVO.getDistName())) {
            resendVO.setDistName(order.getDistName());
        }
        // 地区码
        // resendVO.setAreaCoding(0);
        // 备注
        if (StringUtils.isEmpty(resendVO.getRemark())) {
            resendVO.setRemark("");
        }
        /**
         * 填充仓库相关字段
         */
        // 仓库Id
        if (StringUtils.isEmpty(resendVO.getStorId())) {
            resendVO.setStorId(order.getStorId());
        }
        // 根据仓库id查询仓库相关信息
        Stor storModel = storService.selectStorDetail(resendVO.getStorId());
        // 仓库编码
        resendVO.setStorCode(storModel.getStorCode());
        // 仓库名称
        resendVO.setStorName(storModel.getStorName());
        /**
         * 填充物流公司相关字段
         */
        // 物流公司Id
        if (StringUtils.isEmpty(resendVO.getLgstId())) {
            resendVO.setLgstId(order.getLgstId());
        }
        Logistics lgstModel = logisticsService.selectLgstDetail(resendVO.getLgstId());
        // 物流公司编码
        resendVO.setLgstCode(lgstModel.getLgstCode());
        // 物流公司
        resendVO.setLgstName(lgstModel.getLgstName());
        // 取消状态
        // resendVO.setCancelStatus("n");
        // 补发原因
        if (StringUtils.isEmpty(resendVO.getResendReasonName())) {
            resendVO.setResendReasonName("ReplacementReason");
        }

        return resendVO;
    }

    /**
     * generateReturnCodeWithType:编码生成方法 <br/>
     *
     * @param codeType
     * @param shopId
     * @return
     * @throws Exception
     */
    private String generateReturnCodeWithType(String codeType, String shopId) throws Exception {
        ShopVO shop = shopService.getShopById(shopId);
        ApolloMap<String, Object> params = new ApolloMap<String, Object>();
        ProjectVO project = projectManagerService.findProjectById(shop.getPrjId());
        String prjShortName = project.getPrjShortName();
        String returnCode = codeType + prjShortName + CodeUtil.getCode();
        return returnCode;
    }

    /**
     * delResendSkus:删除补发单明细
     *
     * @param resend
     * @throws Exception
     */
    private void delResendSku(ResendVO resend) throws Exception {
        AfterSaleResendSku resendSku = new AfterSaleResendSku();
        resendSku.setResendId(resend.getResendId());
        resendSku.setDeleted(YesNoConst.YES);
        resendSkuDAO.updateByResendSkuByResend(resendSku);
    }

    /**
     * saveResendSkus:保存补发单明细
     *
     * @param resend
     * @return
     * @throws Exception
     */
    private Boolean saveResendSkus(ResendVO resend, List<AfterSaleResendSku> list) throws Exception {
        int count = 0;
        Boolean saveResendSku = false;
        for (int i = 0; i < list.size(); i++) {
            AfterSaleResendSku resendSku = list.get(i);
            // 补发单Id
            resendSku.setResendId(resend.getResendId());
            // 创建时间
            if (StringUtils.isEmpty(resendSku.getResendId())) {
                resendSku.setCreateTime(new Date());
            }
            // 修改时间
            resendSku.setUpdateTime(new Date());
            // 删除标记
            resendSku.setDeleted("n");

            if (StringUtils.isEmpty(resendSku.getResendSkuId())) {
                // 新增补发单商品
                resendSku.setResendSkuId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
                int insertResendSku = resendSkuDAO.insertResendSku(resendSku);
                if (insertResendSku > 0) {
                    count++;
                }
            } else {
                // 更新补发单
                int updateUpdate = resendSkuDAO.updateByResendSkuIdSelective(resendSku);
                if (updateUpdate > 0) {
                    count++;
                }
            }
        }
        if (count == list.size()) {
            saveResendSku = true;
        }
        return saveResendSku;
    }

    /**
     * auditResend:审核补发单
     */
    public Map<String, Object> auditResend(ArrayList<String> resendIds) throws Exception {

        Map<String, Object> returnValue = new HashMap<String, Object>();
        String errMsg = "以下补发单审核失败!\\n";

        if (null != resendIds && resendIds.size() > 0) {
            for (String resendId : resendIds) {
                ResendVO result = getResendDetailById(resendId);
                if (ResendStatus.VERIFY.equals(result.getResendStatus()) && ResendCancelStatus.N.equals(result.getCancelStatus())) {
                	if (StringUtils.isEmpty(result.getLgstNo())) {
                		errMsg = errMsg + "补发单编号为：【" + result.getResendCode() + "】的补发单没有设置快递单号\\n";
                		continue;
                	}
                    // 用于判断审核的变量
                    int falseStatus = 0;
                    // 获取补发单中的商品列表数据
                    List<ResultdSkuVO> resultSkuVOList = result.getResultSkuVOList();
                    String errQty = "商品（";
                    String errStock = "商品（";
                    String unOrder = "";
                    for (int i = 0; i < resultSkuVOList.size(); i++) {
                        // 订单商品补发商品数量大于订购数量
                        if (resultSkuVOList.get(i).getResendQty() > resultSkuVOList.get(i).getOrderQty()) {
                            errQty = errQty + resultSkuVOList.get(i).getGoodsCode() + "）补发数大于订购数\\n";
                            falseStatus++;
                            break;
                        }
                        // 补发单审核后，发货仓库中对应的可分派数变为负数的
                        StockVO stockVO = stockService.getStock(result.getEntId(), result.getPrjId(), resultSkuVOList.get(i).getSkuId(),
                                result.getStorId());
                        if (null != stockVO) {
                            if (stockVO.getCanallotQty() < 0) {
                                errStock = errStock + resultSkuVOList.get(i).getGoodsCode() + "）可分派数为负数\\n";
                                falseStatus++;
                                break;
                            } else if (stockVO.getCanallotQty() < resultSkuVOList.get(i).getResendQty()) {
                                errStock = errStock + resultSkuVOList.get(i).getGoodsCode() + "）可分派数不足\\n";
                                falseStatus++;
                                break;
                            }

                        } else {
                            errStock = errStock + resultSkuVOList.get(i).getGoodsCode() + "）库存信息不存在\\n";
                            falseStatus++;
                            break;
                        }
                    }
                    // 补发单存在非订单商品
                    if (result.getResendSkuList().size() > 0) {
                        unOrder = "存在非订单商品\\n";
                        falseStatus++;
                    }
                    if (falseStatus == 0) {
                        result.setResendStatus(ResendStatus.DELIVER);
                        result.setUpdateTime(new Date());
                        result.setApprTime(new Date());
                        resendDAO.updateByPrimaryKeySelective(result);
                        // 创建发货单
                        ShiporderVO shiporderVO = getShiporderVODetail(result, "auditResend");
                        shiporderService.insertSelectiveShiporder(shiporderVO);
                        // 添加发货单商品
                        List<ShiporderSkuVO> list = shiporderVO.getShiporderSkuList();
                        for (int i = 0; i < list.size(); i++) {
                            ShiporderSkuVO shiporderSkuVO = list.get(i);
                            shiporderService.insertSelectiveShiporderSku(shiporderSkuVO);
                        }
                        // 更新库存数
                        for (ShiporderSkuVO shiporderSkuInfo : list) {
                            StockVO stockVO = new StockVO();
                            stockVO.setEntId(shiporderVO.getEntId());
                            stockVO.setSkuId(shiporderSkuInfo.getSkuId());
                            stockVO.setStorId(shiporderVO.getStorId());
                            stockVO.setSourceCode(shiporderVO.getShiporderCode());
                            stockVO.setTag("审核补发单生成发货单");
                            if (StringUtils.isNotBlank(shiporderSkuInfo.getQty()) && StringUtils.isNumeric(shiporderSkuInfo.getQty())) {
                                int qty = Integer.parseInt(shiporderSkuInfo.getQty());
                                stockVO.setUnallotQty(qty * -1);
                                stockVO.setAllotQty(qty);
                            }
                            stockService.updateStock(stockVO);
                        }
                        returnValue.put("result", "success");
                    } else {
                        errMsg = errMsg + "编号为：【" + result.getResendCode() + "】的补发单";

                        if (StringUtils.isNotEmpty(unOrder)) {
                            errMsg = errMsg + unOrder;
                            if (!"商品（".equals(errQty)) {
                                errMsg = errMsg.substring(0, errMsg.lastIndexOf("\\n")) + "且" + errQty;
                            }
                            if (!"商品（".equals(errStock)) {
                                errMsg = errMsg.substring(0, errMsg.lastIndexOf("\\n")) + "且" + errStock;
                            }
                        } else {
                            if (!"商品（".equals(errQty)) {
                                errMsg = errMsg + errQty;
                            }
                            if (!"商品（".equals(errStock)) {
                                errMsg = errMsg + errStock;
                            }
                        }
                    }

                } else {
                    errMsg = errMsg + "状态错误！\\n补发单编号为：【" + result.getResendCode() + "】的补发单不是审核所要求的登记状态的未取消的补发单\\n";
                }
            }

        } else {
            returnValue.put("msg", "请至少选择一条补发单！");
            returnValue.put("result", "failed");
        }
        if (!"以下补发单审核失败!\\n".equals(errMsg)) {
            returnValue.put("msg", errMsg);
            returnValue.put("result", "failed");
        } else {
            returnValue.put("msg", "审核成功！");
            returnValue.put("result", "success");
        }
        return returnValue;
    }

    /**
     * checkResends：检查补发单，为强制审核做准备
     */
    @Override
    public Map<String, String> checkResends(String resendIds) throws Exception {
        Map<String, String> returnValue = new HashMap<String, String>();
        String errMsg = "";
        // List<String> idlist=new ArrayList<String>();

        if (StringUtils.isNotBlank(resendIds)) {
            String[] temp = resendIds.split(",");
            if (temp.length > 0) {
                for (int j = 0; j < temp.length; j++) {
                    ResendVO result = getResendDetailById(temp[j]);
                    if (ResendStatus.VERIFY.equals(result.getResendStatus()) && ResendCancelStatus.N.equals(result.getCancelStatus())) {
                        // 用于判断审核的变量
                        int falseStatus = 0;
                        // 获取补发单中的商品列表数据
                        List<ResultdSkuVO> resultSkuVOList = result.getResultSkuVOList();
                        String errQty = "商品（";
                        String unOrder = "";
                        for (int i = 0; i < resultSkuVOList.size(); i++) {
                            // 订单商品补发商品数量大于订购数量
                            if (resultSkuVOList.get(i).getResendQty() > resultSkuVOList.get(i).getOrderQty()) {
                                errQty = errQty + resultSkuVOList.get(i).getGoodsCode() + "）补发数大于订购数\\n";
                                falseStatus++;
                                break;
                            }
                        }
                        // 补发单存在非订单商品
                        if (result.getResendSkuList().size() > 0) {
                            unOrder = "存在非订单商品\\n";
                            falseStatus++;
                        }
                        if (falseStatus == 0) {
                            returnValue.put("result", "success");
                        } else {
                            errMsg = errMsg + "编号为：【" + result.getResendCode() + "】的补发单";
                            if (StringUtils.isNotEmpty(unOrder)) {
                                errMsg = errMsg + unOrder;
                                if (!"商品（".equals(errQty)) {
                                    errMsg = errMsg.substring(0, errMsg.lastIndexOf("\\n")) + "且" + errQty;
                                }
                            } else {
                                if (!"商品（".equals(errQty)) {
                                    errMsg = errMsg + errQty;
                                }
                            }
                        }

                    } else {
                        errMsg = errMsg + "状态错误！\\n补发单编号为：【" + result.getResendCode() + "】的补发单不是审核所要求的登记状态的未取消的补发单\\n";
                    }

                }

            } else {
                returnValue.put("msg", "请至少选择一条补发单！");
                returnValue.put("result", "failed");
            }
        }
        if (StringUtils.isNotBlank(errMsg)) {
            errMsg = errMsg + "是否执行强制审核？";
            returnValue.put("msg", errMsg);
            returnValue.put("result", "failed");
            returnValue.put("data", resendIds);
            // returnValue.put("resendIds", idlist);
        } else {
            returnValue.put("msg", "审核成功！");
            returnValue.put("result", "success");
            returnValue.put("data", "");
        }
        return returnValue;
    }

    /**
     * 强制审核补发单
     *
     * @param resendVO
     * @return
     * @throws Exception
     */
    public Map<String, Object> mandatoryAuditResend(String resendIds) throws Exception {
        Map<String, Object> returnValue = new HashMap<String, Object>();
        String errMsg = "以下补发单强制审核失败，可分派数不足\\n";

        if (StringUtils.isNotBlank(resendIds)) {
            String[] temp = resendIds.split(",");
            if (temp.length > 0) {
                for (int j = 0; j < temp.length; j++) {
                    ResendVO result = getResendDetailById(temp[j]);
                    if (ResendStatus.VERIFY.equals(result.getResendStatus()) && ResendCancelStatus.N.equals(result.getCancelStatus())) {
                        // 用于判断审核的变量
                        int falseStatus = 0;
                        // 获取补发单中的商品列表数据
                        String errStock = "商品（";
                        // 判断订单商品的库存情况
                        List<ResultdSkuVO> resultSkuVOList = result.getResultSkuVOList();
                        for (int i = 0; i < resultSkuVOList.size(); i++) {
                            // 补发单审核后，发货仓库中对应的可分派数变为负数的
                            StockVO stockVO = stockService.getStock(result.getEntId(), result.getPrjId(), resultSkuVOList.get(i).getSkuId(),
                                    result.getStorId());
                            if (null != stockVO) {
                                if (stockVO.getCanallotQty() < 0) {
                                    // 可分派数变为负数
                                    errStock = errStock + resultSkuVOList.get(i).getGoodsCode() + "）\\n";
                                    falseStatus++;
                                    break;
                                } else if (stockVO.getCanallotQty() < resultSkuVOList.get(i).getResendQty()) {
                                    // 可分派数小于补发数
                                    errStock = errStock + resultSkuVOList.get(i).getGoodsCode() + "）\\n";
                                    falseStatus++;
                                    break;
                                }
                            } else {
                                // 库存信息不存在
                                errStock = errStock + resultSkuVOList.get(i).getGoodsCode() + "）\\n";
                                falseStatus++;
                                break;
                            }
                        }
                        // 判断非订单商品的库存情况
                        List<AfterSaleResendSku> resendSkuList = result.getResendSkuList();
                        for (int i = 0; i < resendSkuList.size(); i++) {
                            // 补发单审核后，发货仓库中对应的可分派数变为负数的
                            StockVO stockVO = stockService.getStock(result.getEntId(), result.getPrjId(), resendSkuList.get(i).getSkuId(),
                                    result.getStorId());
                            if (null != stockVO) {
                                if (stockVO.getCanallotQty() < 0) {
                                    // 可分派数变为负数
                                    if ("商品（".equals(errStock)) {
                                        errStock = errStock + resendSkuList.get(i).getGoodsCode() + "）\\n";
                                    } else {
                                        errStock = errStock.substring(0, errStock.lastIndexOf("）\\n")) + ","
                                                + resendSkuList.get(i).getGoodsCode() + "）\\n";
                                    }
                                    falseStatus++;
                                    break;
                                } else if (stockVO.getCanallotQty() < resendSkuList.get(i).getQty()) {
                                    // 可分派数小于补发数
                                    if ("商品（".equals(errStock)) {
                                        errStock = errStock + resendSkuList.get(i).getGoodsCode() + "）\\n";
                                    } else {
                                        errStock = errStock.substring(0, errStock.lastIndexOf("）\\n")) + ","
                                                + resendSkuList.get(i).getGoodsCode() + "）\\n";
                                    }
                                    falseStatus++;
                                    break;
                                }
                            } else {
                                // 库存信息不存在
                                if ("商品（".equals(errStock)) {
                                    errStock = errStock + resendSkuList.get(i).getGoodsCode() + "）\\n";
                                } else {
                                    errStock = errStock.substring(0, errStock.lastIndexOf("）\\n")) + "," + resendSkuList.get(i).getGoodsCode()
                                            + "）\\n";
                                }
                                falseStatus++;
                                break;
                            }
                        }
                        if (falseStatus == 0) {
                            result.setResendStatus(ResendStatus.DELIVER);
                            result.setUpdateTime(new Date());
                            result.setApprTime(new Date());
                            resendDAO.updateByPrimaryKeySelective(result);
                            // 创建发货单
                            ShiporderVO shiporderVO = getShiporderVODetail(result, "mandatoryAuditResend");
                            shiporderService.insertSelectiveShiporder(shiporderVO);
                            // 添加发货单商品
                            List<ShiporderSkuVO> list = shiporderVO.getShiporderSkuList();
                            for (int i = 0; i < list.size(); i++) {
                                ShiporderSkuVO shiporderSkuVO = list.get(i);
                                shiporderService.insertSelectiveShiporderSku(shiporderSkuVO);
                            }
                            // 更新库存数
                            for (ShiporderSkuVO shiporderSkuInfo : list) {
                                StockVO stockVO = new StockVO();
                                stockVO.setEntId(shiporderVO.getEntId());
                                stockVO.setSkuId(shiporderSkuInfo.getSkuId());
                                stockVO.setStorId(shiporderVO.getStorId());
                                stockVO.setSourceCode(shiporderVO.getShiporderCode());
                                stockVO.setTag("审核补发单生成发货单");
                                if (StringUtils.isNotBlank(shiporderSkuInfo.getQty()) && StringUtils.isNumeric(shiporderSkuInfo.getQty())) {
                                    int qty = Integer.parseInt(shiporderSkuInfo.getQty());
                                    stockVO.setUnallotQty(qty * -1);
                                    stockVO.setAllotQty(qty);
                                }
                                stockService.updateStock(stockVO);
                            }
                            returnValue.put("result", "success");
                        } else {
                            errMsg = errMsg + "编号为：【" + result.getResendCode() + "】的补发单";
                            if (!"商品（".equals(errStock)) {
                                errMsg = errMsg + errStock;
                            }
                        }

                    } else {
                        errMsg = errMsg + "状态错误！\\n补发单编号为：【" + result.getResendCode() + "】的补发单不是强制审核所要求的登记状态的未取消的补发单\\n";
                    }
                }

            } else {
                returnValue.put("msg", "请至少选择一条补发单！");
                returnValue.put("result", "failed");
            }
        }
        if (!"以下补发单强制审核失败，可分派数不足\\n".equals(errMsg)) {
            returnValue.put("msg", errMsg);
            returnValue.put("result", "failed");
        } else {
            returnValue.put("msg", "审核成功！");
            returnValue.put("result", "success");
        }
        return returnValue;
    }

    @SuppressWarnings("rawtypes")
    private ShiporderVO getShiporderVODetail(ResendVO resendVO, String type) throws Exception {

        ShiporderVO shiporderVO = new ShiporderVO();
        // 创建时间
        shiporderVO.setCreateTime(new Date());
        // 设置企业Id
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        Iterator iterator = currentUser.getEnterpriseMap().keySet().iterator();
        String entId = (String) iterator.next();
        shiporderVO.setEntId(entId);
        // 设置项目Id
        String prjId = currentUser.getCurrentProject().getPrjId();
        shiporderVO.setPrjId(prjId);
        // 平台交易号
        shiporderVO.setTradeCode(resendVO.getEcTradeCode());
        // 设置发货单Id
        String shiporderId = java.util.UUID.randomUUID().toString().replace("-", "");
        shiporderVO.setShiporderId(shiporderId);
        // 设置发货单编码
        String prjShortName = currentUser.getCurrentProject().getPrjShortName();
        shiporderVO.setShiporderCode("SO" + prjShortName + CodeUtil.getCode());
        // 来源Id
        shiporderVO.setSourceId(resendVO.getResendId());
        // 来源单号
        shiporderVO.setSourceCode(resendVO.getResendCode());
        // 来源类型
        shiporderVO.setSourceType("rs");
        // 店铺Id
        shiporderVO.setShopId(resendVO.getShopId());
        // 店铺名称
        shiporderVO.setShopName(resendVO.getShopName());
        // 根据店铺Id查询店铺信息
        ShopVO shopVO = new ShopVO();
        shopVO.setShopId(resendVO.getShopId());
        Shop shop = shopService.findByWhere(shopVO).get(0);
        // 店铺名称
        // shiporderVO.setShopName(shop.getShopName());
        // 店铺账号
        shiporderVO.setShopAccount(shop.getShopAccount());
        // 来源单号
        shiporderVO.setSourceType("rs");
        // 物流公司Id
        shiporderVO.setLgstId(resendVO.getLgstId());
        // 物流公司
        shiporderVO.setLgstName(resendVO.getLgstName());
        // 物流公司编码
        shiporderVO.setLgstCode(resendVO.getLgstCode());
        // 快递单号
        shiporderVO.setLgstNo(resendVO.getLgstNo());
        // 仓库Id
        shiporderVO.setStorId(resendVO.getStorId());
        // 仓库
        shiporderVO.setStorName(resendVO.getStorName());
        // 仓库编码
        shiporderVO.setStorCode(resendVO.getStorCode());
        // source_platform_code 来源平台编码(TB淘宝、TM天猫、JD京东)
        shiporderVO.setSourcePlatformCode(resendVO.getShopType());
        // 买家昵称
        shiporderVO.setBuyerNick(resendVO.getBuyerNick());
        // 备注
        shiporderVO.setRemark(resendVO.getRemark());
        // 收货人
        shiporderVO.setCons(resendVO.getCons());
        // 收货人手机
        shiporderVO.setConsMobile(resendVO.getConsMobile());
        // 收货人电话
        shiporderVO.setConsTel(resendVO.getConsTel());
        // 省名称
        shiporderVO.setProvName(resendVO.getProvName());
        // 市名称
        shiporderVO.setCityName(resendVO.getCityName());
        // 区名称
        shiporderVO.setDistName(resendVO.getDistName());
        // 收货人地址
        shiporderVO.setConsAddr(resendVO.getConsAddr());

        // 设置发货单商品信息
        List<ShiporderSkuVO> list = new ArrayList<ShiporderSkuVO>();
        if ("auditResend".equals(type)) {
            for (int i = 0; i < resendVO.getResultSkuVOList().size(); i++) {
                ShiporderSkuVO shiporderSkuVO = new ShiporderSkuVO();
                // 发货单明细Id
                shiporderSkuVO.setShiporderSkuId(java.util.UUID.randomUUID().toString().replace("-", ""));
                // 发货单id
                shiporderSkuVO.setShiporderId(shiporderId);
                // 订单商品id
                shiporderSkuVO.setOrderSkuId(resendVO.getResultSkuVOList().get(i).getOrderSkuId());
                // 子订单编号(平台oid)
                shiporderSkuVO.setOid(resendVO.getResultSkuVOList().get(i).getOrderId());
                // 平台交易号
                shiporderSkuVO.setTradeCode(resendVO.getEcTradeCode());
                // 商品id
                shiporderSkuVO.setGoodsId(resendVO.getResultSkuVOList().get(i).getGoodsId());
                // 商品商家编码
                shiporderSkuVO.setGoodsCode(resendVO.getResultSkuVOList().get(i).getGoodsCode());
                // 商品名称
                shiporderSkuVO.setGoodsName(resendVO.getResultSkuVOList().get(i).getGoodsName());
                // 规格id
                shiporderSkuVO.setSkuId(resendVO.getResultSkuVOList().get(i).getSkuId());
                // 规格商家编码
                shiporderSkuVO.setSkuCode(resendVO.getResultSkuVOList().get(i).getSkuCode());
                // 规格名称
                shiporderSkuVO.setSkuName(resendVO.getResultSkuVOList().get(i).getSkuName());
                // 实际单价(拍单价)
                shiporderSkuVO.setDivideGoodsFee(resendVO.getResultSkuVOList().get(i).getDivideGoodsFee().toString());
                // 数量
                shiporderSkuVO.setQty(resendVO.getResultSkuVOList().get(i).getResendQty().toString());
                list.add(shiporderSkuVO);
            }
        } else {
            // 添加补发单对应的订单商品
            for (int i = 0; i < resendVO.getResultSkuVOList().size(); i++) {
                ShiporderSkuVO shiporderSkuVO = new ShiporderSkuVO();
                // 发货单明细Id
                shiporderSkuVO.setShiporderSkuId(java.util.UUID.randomUUID().toString().replace("-", ""));
                // 发货单id
                shiporderSkuVO.setShiporderId(shiporderId);
                // 订单商品id
                shiporderSkuVO.setOrderSkuId(resendVO.getResultSkuVOList().get(i).getOrderSkuId());
                // 子订单编号(平台oid)
                shiporderSkuVO.setOid(resendVO.getResultSkuVOList().get(i).getOrderId());
                // 平台交易号
                shiporderSkuVO.setTradeCode(resendVO.getEcTradeCode());
                // 商品id
                shiporderSkuVO.setGoodsId(resendVO.getResultSkuVOList().get(i).getGoodsId());
                // 商品商家编码
                shiporderSkuVO.setGoodsCode(resendVO.getResultSkuVOList().get(i).getGoodsCode());
                // 商品名称
                shiporderSkuVO.setGoodsName(resendVO.getResultSkuVOList().get(i).getGoodsName());
                // 规格id
                shiporderSkuVO.setSkuId(resendVO.getResultSkuVOList().get(i).getSkuId());
                // 规格商家编码
                shiporderSkuVO.setSkuCode(resendVO.getResultSkuVOList().get(i).getSkuCode());
                // 规格名称
                shiporderSkuVO.setSkuName(resendVO.getResultSkuVOList().get(i).getSkuName());
                // 实际单价(拍单价)
                shiporderSkuVO.setDivideGoodsFee(resendVO.getResultSkuVOList().get(i).getDivideGoodsFee().toString());
                // 数量
                shiporderSkuVO.setQty(resendVO.getResultSkuVOList().get(i).getResendQty().toString());
                list.add(shiporderSkuVO);
            }
            // 添加补发单对应的非订单商品
            for (int i = 0; i < resendVO.getResendSkuList().size(); i++) {
                ShiporderSkuVO shiporderSkuVO = new ShiporderSkuVO();
                // 发货单明细Id
                shiporderSkuVO.setShiporderSkuId(java.util.UUID.randomUUID().toString().replace("-", ""));
                // 发货单id
                shiporderSkuVO.setShiporderId(shiporderId);
                // 订单商品id
                shiporderSkuVO.setOrderSkuId(resendVO.getResendSkuList().get(i).getResendSkuId());
                // 子订单编号(平台oid)
                shiporderSkuVO.setOid(resendVO.getResendSkuList().get(i).getResendId());
                // 平台交易号
                shiporderSkuVO.setTradeCode(resendVO.getEcTradeCode());
                // 商品id
                shiporderSkuVO.setGoodsId(resendVO.getResendSkuList().get(i).getGoodsId());
                // 商品商家编码
                shiporderSkuVO.setGoodsCode(resendVO.getResendSkuList().get(i).getGoodsCode());
                // 商品名称
                shiporderSkuVO.setGoodsName(resendVO.getResendSkuList().get(i).getGoodsName());
                // 规格id
                shiporderSkuVO.setSkuId(resendVO.getResendSkuList().get(i).getSkuId());
                // 规格商家编码
                shiporderSkuVO.setSkuCode(resendVO.getResendSkuList().get(i).getSkuCode());
                // 规格名称
                shiporderSkuVO.setSkuName(resendVO.getResendSkuList().get(i).getSkuName());
                // 实际单价(拍单价)
                shiporderSkuVO.setDivideGoodsFee(resendVO.getResendSkuList().get(i).getDivideGoodsFee().toString());
                // 数量
                shiporderSkuVO.setQty(resendVO.getResendSkuList().get(i).getQty().toString());
                list.add(shiporderSkuVO);
            }

        }
        shiporderVO.setShiporderSkuList(list);
        return shiporderVO;
    }

    /**
     * getResendSku:根据补发单ID获取补发单.
     *
     * @param resendId
     * @return
     */
    public List<AfterSaleResendSku> getResendSku(String resendId) throws Exception {
        List<AfterSaleResendSku> returnValue = resendSkuDAO.selectResendSkubyresendId(resendId);
        return returnValue;
    }

    /**
     * 根据查询条件查询补发单列表.
     *
     * @throws Exception
     */
    public PageInfo<ResendVO> findByWhere(int page, int rows, ResendVO param) throws Exception {
        PageInfo<ResendVO> resendVOList = findPage(page, rows, "pageSelectResendByCondition", param);
        return resendVOList;
    }

    @Override
    public AfterSaleResendSku selectResendSkubyresendSkuId(String resendSkuId) throws Exception {
        return resendSkuDAO.selectResendSkubyresendSkuId(resendSkuId);
    }

    /**
     * findCounts：补发的各种count
     */
    public List<ResendVO> findCounts(ResendVO param) throws Exception {
        List<ResendVO> list = findPage(STATEMENT_SELECT_COUNT_BY_STATUS, param);
        return list;
    }

    /**
     * getResendDetailById：根据补发单id获取补发单
     */
    public ResendVO getResendDetailById(String resendId) throws Exception {
        ResendVO returnValue = resendDAO.selectDetailByPrimaryKey(resendId);
        
        List<ResultdSkuVO> resultSkuList = returnValue.getResultSkuVOList();
        for (ResultdSkuVO afterSaleResendSku : resultSkuList) {
            String snCode = StringUtils.EMPTY;
            if(YesNoConst.YES.equals(afterSaleResendSku.getIsOrderSku())) {
                snCode = snCodeExtractor.getSnCodeBySourceSkuId(afterSaleResendSku.getSourceSkuId(),"rs",resendId);
            }else if("r".equalsIgnoreCase(afterSaleResendSku.getIsOrderSku())){
                snCode = snCodeExtractor.getSnCodeBySourceSkuId(afterSaleResendSku.getResendSkuId(),"rs",resendId);
            }else {
                snCode = StringUtils.EMPTY;
            }
            afterSaleResendSku.setSn(snCode);
        }
        
        List<AfterSaleResendSku> resendSkuList = returnValue.getResendSkuList();
        for (AfterSaleResendSku afterSaleResendSku : resendSkuList) {
            String snCode = StringUtils.EMPTY;
            if(YesNoConst.YES.equals(afterSaleResendSku.getIsOrderSku())) {
                snCode = snCodeExtractor.getSnCodeBySourceSkuId(afterSaleResendSku.getSourceSkuId(),"rs",resendId);
            }else{
                snCode = snCodeExtractor.getSnCodeBySourceSkuId(afterSaleResendSku.getResendSkuId(),"rs",resendId);
            }
            afterSaleResendSku.setSn(snCode);
        }
        return returnValue;
    }

    /**
     * completeResends：完成补发单
     */
    @Override
    public String completeResends(String resendCode) throws Exception {
        String returnMsg = "完成失败，不存在此补发单";
        ResendVO resend = new ResendVO();
        resend.setResendCode(resendCode);
        List<ResendVO> resendList = resendDAO.seleteByCondition(resend);
        if (resendList.size() > 0) {
            resendList.get(0).setFinishTime(new Date());
            resendList.get(0).setResendStatus(ResendStatus.COMPLETE);
            int updateUpdate = resendDAO.updateByPrimaryKeySelective(resendList.get(0));
            if (updateUpdate > 0) {
                returnMsg = "完成补发单";
            }
        }
        return returnMsg;
    }

    /**
     * updateResends:修改补发单
     */
    @Override
    public int updateResends(ResendVO resend) throws Exception {
        return resendDAO.updateByPrimaryKeySelective(resend);
    }

    /**
     * deleteResendbyID：删除补发单
     */
    @Override
    public String deleteResendbyID(String resendIds) throws Exception {
        String returnMsg = "";
        String[] eventIdArray = StringUtils.split(resendIds, ",");
        ResendVO resend = new ResendVO();

        resend.getIdArray().addAll(Arrays.asList(eventIdArray));
        resend.setDeleted(YesNoConst.YES);

        int updateUpdate = resendDAO.updateByPrimaryKeySelective(resend);
        if (updateUpdate > 0) {

            // 更新系统订单补发单的状态
            // 通过补发单单id获取订单id
            AfterSaleResend AfterSaleResendForOne = resendDAO.selectResendByResendID(eventIdArray[0].toString());
            if (AfterSaleResendForOne != null) {
                String strSourceId = AfterSaleResendForOne.getSourceId();
                if (StringUtils.isNotBlank(strSourceId)) {
                    // 通过来源id获取未废弃补发单信息
                    List<AfterSaleResend> afterSaleResendBySourceID = resendDAO.selectResendBySourceID(strSourceId);
                    if (afterSaleResendBySourceID == null || afterSaleResendBySourceID.size() <= 0) {
                        // 没有 未废弃的补发单，更新订单补发单标识为 n
                        OrderVO orderVOUpdate = new OrderVO();
                        orderVOUpdate.setOrderId(strSourceId);
                        orderVOUpdate.setHasResend("n");
                        int iOrderUpdate = orderDao.update(orderVOUpdate);
                    }
                }
            }

            returnMsg = "删除成功";
        }
        return returnMsg;
    }
    
    @Override
    public List<AfterSaleResend> findResendByOrderId(String orderId) throws Exception {
        return resendDAO.selectResendBySourceID(orderId);
    }

    @Override
    public int getUnGoingCount(Map<String, String> paramMap) throws Exception {
        return resendDAO.getUnGoingCount(paramMap);
    }

}
